<?php

namespace app\admin\controller\mall;

use app\admin\model\MallExpress;
use app\admin\model\MallGoods;
use app\admin\model\MallOrder;
use app\api\help\SendMsg;
use app\api\model\AllInPay;
use app\api\model\MallCollage;
use app\api\model\MallTradeRecordLog;
use app\api\model\MallUser;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="订单")
 */
class Order extends AdminController
{
    
    
    public function __construct(App $app)
    {
        parent::__construct($app);
        
        $this->model = new \app\admin\model\MallOrder();
        
    }
    
    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $where[] = ['order_status', '>', 0];
            $where[] = ['ea_mall_order.is_virtual', '=', 0];
            $count   = $this->model
                ->withJoin(['goods', 'user', 'collage'], 'left')
                ->where($where)
                ->value('count(1)');
            $list    = $this->model
                ->withJoin(['goods', 'user', 'collage'], 'left')
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data    = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

//    /**
//     * @NodeAnotation(title="分状态列表")
//     */
    public function statusIndex()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $where[] = ['order_status', '=', input('status')];
            $where[] = ['ea_mall_order.is_virtual', '=', 0];
            $count   = $this->model
                ->with(['goods', 'user', 'collage'])
                ->where($where)
                ->count();
            $list    = $this->model
                ->with(['goods', 'user', 'collage'])
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data    = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    
    /**
     * @NodeAnotation(title="订单详情")
     */
    public function detail($id)
    {
        $row = $this->model->with(['goods', 'user'])->find($id)->toArray();
        empty($row) && $this->error('数据不存在');
        switch ($row[ 'order_status' ]) {
            case 0:
                $row[ 'order_status' ] = '未支付';
                break;
            case 1:
                $row[ 'order_status' ] = '拼团已结束';
                break;
            case 10:
                $row[ 'order_status' ] = '进行中';
                break;
            case 20:
                $row[ 'order_status' ] = '取消';
                break;
            case 30:
                $row[ 'order_status' ] = '拼团成功';
                break;
            case 40:
                $row[ 'order_status' ] = '拼团失败';
                break;
            case 50:
                $row[ 'order_status' ] = '已发货';
                break;
            case 60:
                $row[ 'order_status' ] = '已完成';
                break;
            case 70:
                $row[ 'order_status' ] = '已退款';
                break;
        }
        $row[ 'collage_num' ] = MallCollage::where([['collage_id', '=', $row[ 'collage_id' ]]])->value('collage_num') ?? 0;
        $row[ 'order_num' ]   = MallOrder::where([['u_collage_id', '=', $row[ 'collage_id' ]], ['order_status', 'in', '10,30,50,60']])->count() ?? 0;
        $row[ 'order_user' ]  = [];
        if ($row[ 'order_num' ] > 0) {
            $userIds             = MallOrder::where([['u_collage_id', '=', $row[ 'collage_id' ]], ['order_status', 'in', '10,30,50,60']])->column('user_id');
            $row[ 'order_user' ] = MallUser::where([['id', 'in', $userIds]])->select()->toArray();
        }
        $row[ 'user_order_num' ]  = MallOrder::where([['u_collage_id', '=', $row[ 'collage_id' ]], ['order_status', 'in', '10,30,50,60'], ['uid', '=', $row[ 'user_id' ]]])->count();
        $row[ 'user_order_user' ] = [];
        if ($row[ 'user_order_num' ] > 0) {
            $userIds                  = MallOrder::where([['u_collage_id', '=', $row[ 'collage_id' ]], ['order_status', 'in', '10,30,50,60'], ['uid', '=', $row[ 'user_id' ]]])->column('user_id');
            $row[ 'user_order_user' ] = MallUser::where([['id', 'in', $userIds]])->select()->toArray();
        }
        $row[ 'total_price' ]     = getPrice($row[ 'total_price' ]);
        $row[ 'order_price' ]     = getPrice($row[ 'order_price' ]);
        $row[ 'pay_price' ]       = getPrice($row[ 'pay_price' ]);
        $row[ 'pay_balance' ]     = getPrice($row[ 'pay_balance' ]);
        $row[ 'failure_subsidy' ] = getPrice($row[ 'failure_subsidy' ]);
        $this->assign('row', $row) ?? 0;
        return $this->fetch();
    }


//    /**
//     * @NodeAnotation(title="获取拼团列表")
//     */
    public function getCollage()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                $this->selectWhere = [
                    ['status', '=', 1],
                    ['delete_time', '=', null],
                ];
                $where             = [
//                    ['start_time', '>', time()],
//                    ['end_time', '<', time()],
                ];
                $data              = MallCollage::where($where)
//                    ->field($fields)
                    ->select()->toArray();
                $goodsIds          = array_column($data, 'goods_id');
                $goods             = MallGoods::where([['id', 'in', $goodsIds]])->select()->toArray();
                $goods             = array_column($goods, null, 'id');
                $collageIds        = array_column($data, 'collage_id');
                $orderCount        = MallOrder::where([['collage_id', 'in', $collageIds], ['order_status', '=', 10]])->field('collage_id,count(1) as count')->group('collage_id')->select()->toArray();
                $orderCount        = array_column($orderCount, null, 'collage_id');
                $returnData        = [];
                foreach ($data as $key => $value) {
                    $returnData[ $key ][ 'collage_id' ] = $value[ 'collage_id' ];
                    $str                                = $goods[ $value[ 'goods_id' ] ][ 'title' ] ?? '';
                    $str                                .= '---' . $value[ 'collage_num' ] . '人团';
                    $count                              = $orderCount[ $value[ 'collage_id' ] ][ 'count' ] ?? 0;
                    $str                                .= '，已有' . $count . '人参与拼团';
                    $returnData[ $key ][ 'goods_name' ] = $str;
                }
                $this->success(null, $returnData);
            }
        }
        return $this->fetch();
    }
    
    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        [$page, $limit, $where] = $this->buildTableParames();
        $header  = [
            ['订单号', 'order_no'],
            ['拼团号', 'collage_no'],
            ['用户名', 'user_name'],
            ['商品名', 'goods_name'],
            ['实际付款金额', 'pay_price'],
            ['订单状态', 'order_status'],
            ['创建时间', 'create_time'],
        ];
        $where[] = ['order_status', '>', 0];
        $where[] = ['ea_mall_order.is_virtual', '=', 0];
        $list    = $this->model
            ->withJoin(['goods', 'user'], 'LEFT')
            ->where($where)
            ->limit(100000)
            ->order($this->sort)
            ->select()
            ->toArray();
        foreach ($list as $key => $value) {
            $list[ $key ][ 'user_name' ]  = $value[ 'user' ][ 'name' ] ?? '';
            $list[ $key ][ 'collage_no' ] = $value[ 'collage' ][ 'collage_no' ] ?? '';
            $list[ $key ][ 'pay_price' ]  = '￥' . $value[ 'pay_price' ] / 100 ?? 0;
            switch ($value[ 'order_status' ]) {
                case 0:
                    $list[ $key ][ 'order_status' ] = '未支付';
                    break;
                case 10:
                    $list[ $key ][ 'order_status' ] = '拼团中';
                    break;
                case 20:
                    $list[ $key ][ 'order_status' ] = '已取消';
                    break;
                case 30:
                    $list[ $key ][ 'order_status' ] = '拼团成功';
                    break;
                case 40:
                    $list[ $key ][ 'order_status' ] = '拼团失败';
                    break;
                case 50:
                    $list[ $key ][ 'order_status' ] = '已发货';
                    break;
                case 60:
                    $list[ $key ][ 'order_status' ] = '已完成';
                    break;
                case 70:
                    $list[ $key ][ 'order_status' ] = '退款';
                    break;
            }
        }
        $fileName = '订单列表' . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }
    
    /**
     * @NodeAnotation(title="允许退款")
     */
    public function permitRefund($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->find();
        if ( !in_array($row->order_status, [10, 30, 60]) || $row->refund_status != 0) {
            $this->error('订单状态异常，请刷新重试');
        }
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->save(['refund_status' => 1, 'order_status' => 70, 'collage_status' => 4]);
            MallCollage::where('collage_id', $row->collage_id)->update(['status' => 0]);
        } catch (\Exception $e) {
            $this->error('允许退款失败');
        }
        $save ? $this->success('允许退款成功') : $this->error('允许退款失败');
    }
    
    /**
     * @NodeAnotation(title="退款")
     */
    public function refund($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->find();
        if ( !in_array($row->order_status, [30, 40, 70]) || $row->refund_status != 10) {
            $this->error('订单状态异常，请刷新重试');
        }
        $row->isEmpty() && $this->error('数据不存在');
        $balance        = MallUser::where('id', $row->user_id)->value('balance');
        $failure_reward = MallGoods::where('id', $row->goods_id)->value('failure_reward');
        
        try {
            //开启事务
            Db::startTrans();
            $collage = MallCollage::where('collage_id', $row->collage_id)->find();
            
            //拼团失败
            MallOrder::resolveCollage($row->toArray());
            $modOrder = ['refund_status' => 20, 'order_status' => 70, 'collage_status' => 4, 'refund_time' => time()];
            if ($row->pay_price > 0) {
                $res = AllInPay::orderRefundInfo($row);
                if ($res[ 'trxstatus' ] == '0000') {
                    AllInPay::afterRefund($row->toArray());
                } else {
                    _throwNewException($res[ 'errmsg' ]);
                }
                $modOrder[ 'refund_status' ] = 40;
            } else {
                $type = 11;
                if ($row->order_status == 40) {
                    $type = 13;
                }
                $modOrder[ 'refund_status' ] = 40;
                $surBalance                  = $balance + $row->pay_balance;
                //加上余额
                if (false === MallUser::where([['id', '=', $row->user_id]])->update(['balance' => $surBalance])) {
                    _throwNewException('退款失败');
                }
                //添加交易记录
                $tradeLogData = [
                    'trade_type'  => $type,
                    'amount'      => $row->pay_balance,
                    'balance'     => $surBalance,
                    'order_id'    => $row->id,
                    'user_id'     => $row->user_id,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                if (false === MallTradeRecordLog::insert($tradeLogData)) {
                    _throwNewException('退款失败');
                }
            }
            $save = $row->save($modOrder);
            //如果拼团未成功
            if (empty($collage->finish_time)) {
                //添加失败奖励
                MallOrder::resolveFailureReward($failure_reward, $row->user_id, $row->id, $row->collage_id);
                if (false === MallCollage::where('collage_id', $row->collage_id)->update(['fail_time' => time()])) {
                    _throwNewException('订单支付失败');
                }
            }
            
            // 提交事务
            Db::commit();
            
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        $save ? $this->success('退款成功') : $this->error('退款失败');
    }
    /**
     * @NodeAnotation(title="发货")
     */
    public function send($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post                   = $this->request->post();
            $post[ 'order_status' ] = 50;
            $post[ 'update_time' ]  = time();
            $rule                   = [];
            $this->validate($post, $rule);
            try {
                $post[ 'express_company' ] = MallExpress::where('id', $post[ 'express_id' ])->value('express_name');
                $post[ 'delivery_time' ]   = time();
                $save                      = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        switch ($row[ 'order_status' ]) {
            case 0:
                $row[ 'order_status' ] = '未支付';
                break;
            case 1:
                $row[ 'order_status' ] = '拼团已结束';
                break;
            case 10:
                $row[ 'order_status' ] = '进行中';
                break;
            case 20:
                $row[ 'order_status' ] = '取消';
                break;
            case 30:
                $row[ 'order_status' ] = '拼团成功';
                break;
            case 40:
                $row[ 'order_status' ] = '拼团失败';
                break;
            case 50:
                $row[ 'order_status' ] = '已发货';
                break;
            case 60:
                $row[ 'order_status' ] = '已完成';
                break;
            case 70:
                $row[ 'order_status' ] = '已退款';
                break;
        }
        $row[ 'collage_num' ] = MallCollage::where([['collage_id', '=', $row[ 'collage_id' ]]])->value('collage_num') ?? 0;
        $row[ 'join_num' ]        = MallCollage::where([['collage_id', '=', $row[ 'collage_id' ]]])->value('join_num') ?? 0;
        $row[ 'total_price' ]     = getPrice($row[ 'total_price' ]);
        $row[ 'order_price' ]     = getPrice($row[ 'order_price' ]);
        $row[ 'pay_price' ]       = getPrice($row[ 'pay_price' ]);
        $row[ 'pay_balance' ]     = getPrice($row[ 'pay_balance' ]);
        $row[ 'failure_subsidy' ] = getPrice($row[ 'failure_subsidy' ]);
        $this->assign('row', $row);
        return $this->fetch();
    }
    
    /**
     * @NodeAnotation(title="确认收货")
     */
    public function confirmOrder($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->find();
        if ( !in_array($row->order_status, [50]) || $row->refund_status != 0) {
            $this->error('订单状态异常，请刷新重试');
        }
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->save(['order_status' => 60, 'receipt_time' => time()]);
        } catch (\Exception $e) {
            $this->error('确认收货失败');
        }
        $save ? $this->success('确认收货成功') : $this->error('确认收货失败');
    }
}